<?php
ob_start();
include 'includes/header.php';
require_once '../config/database.php';

if (!is_admin()) {
    redirect('../login.php');
}

$database = new Database();
$db = $database->getConnection();

// Get all brands
$brands_query = "SELECT * FROM brands ORDER BY name";
$brands = $db->query($brands_query)->fetchAll();

if (isset($_POST['submit'])) {
    $brand_id = $_POST['brand_id'];
    $model_id = $_POST['model_id'];
    $title = sanitize_input($_POST['title']);
    $year = (int)$_POST['year'];
    $price = (float)$_POST['price'];
    $mileage = (int)$_POST['mileage'];
    $fuel_type = $_POST['fuel_type'];
    $transmission = $_POST['transmission'];
    $drive_terrain = $_POST['drive_terrain'];
    $condition_type = $_POST['condition_type'];
    $body_type = $_POST['body_type'];
    $steering = $_POST['steering'];
    $displacement = (int)$_POST['displacement'];
    $model_code = sanitize_input($_POST['model_code']);
    $description = sanitize_input($_POST['description']);
    $features = sanitize_input($_POST['features']);

    // Get uploaded images
    $uploaded_images = json_decode($_POST['uploaded_images'] ?? '[]', true);
    
    // First image becomes the main image
    $main_image = $uploaded_images[0];

    // Insert car details
    $query = "INSERT INTO cars (brand_id, model_id, title, year, price, mileage, 
              fuel_type, transmission, drive_terrain, condition_type, body_type, steering, displacement, 
              model_code, description, features, main_image) 
              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $db->prepare($query);
    if ($stmt->execute([
        $brand_id, $model_id, $title, $year, $price, $mileage,
        $fuel_type, $transmission, $drive_terrain, $condition_type, $body_type, $steering,
        $displacement, $model_code, $description, $features, $main_image
    ])) {
        $car_id = $db->lastInsertId();

        // Add additional images
        if (count($uploaded_images) > 1) {
            $image_query = "INSERT INTO car_images (car_id, image_path) VALUES (?, ?)";
            $image_stmt = $db->prepare($image_query);
            
            // Skip first image as it's already the main image
            for ($i = 1; $i < count($uploaded_images); $i++) {
                $image_stmt->execute([$car_id, $uploaded_images[$i]]);
            }
        }

        set_message('Car added successfully');
        redirect('./manage_cars.php');
    } else {
        set_message('Error adding car', 'danger');
    }
}
?>

<!-- Add jQuery UI CSS and JS -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

<!-- FilePond CSS and JS -->
<link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet">
<link href="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css" rel="stylesheet">
<script src="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.js"></script>
<script src="https://unpkg.com/filepond-plugin-file-validate-type/dist/filepond-plugin-file-validate-type.js"></script>
<script src="https://unpkg.com/filepond/dist/filepond.js"></script>

<div class="container py-4">
    <div class="row">
        <div class="col-12">
            <h2 class="mb-4">Add New Car</h2>
            
            <div class="card shadow">
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Title</label>
                                <input type="text" class="form-control" name="title" id="carTitle" required>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">Brand</label>
                                <select name="brand_id" class="form-select" id="brand-select" required>
                                    <option value="">Select Brand</option>
                                    <?php foreach ($brands as $brand): ?>
                                        <option value="<?php echo $brand['id']; ?>">
                                            <?php echo htmlspecialchars($brand['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">Model</label>
                                <select name="model_id" class="form-select" id="model-select" required disabled>
                                    <option value="">Select Brand First</option>
                                </select>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">Year</label>
                                <select name="year" class="form-select" required>
                                    <?php for($i = date('Y') + 1; $i >= 1990; $i--): ?>
                                        <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                                    <?php endfor; ?>
                                </select>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">Price</label>
                                <input type="number" class="form-control" name="price" step="0.01" required>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">Mileage</label>
                                <input type="number" class="form-control" name="mileage" required>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Fuel Type</label>
                                <select name="fuel_type" class="form-select" required>
                                    <option value="Petrol">Petrol</option>
                                    <option value="Diesel">Diesel</option>
                                    <option value="Electric">Electric</option>
                                    <option value="Hybrid">Hybrid</option>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Transmission</label>
                                <select name="transmission" class="form-select" required>
                                    <option value="Manual">Manual</option>
                                    <option value="Automatic">Automatic</option>
                                    <option value="CVT">CVT</option>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Drive Terrain</label>
                                <select name="drive_terrain" class="form-select" required>
                                    <option value="">Select Drive Terrain</option>
                                    <option value="FWD">Front Wheel Drive (FWD)</option>
                                    <option value="RWD">Rear Wheel Drive (RWD)</option>
                                    <option value="AWD">All Wheel Drive (AWD)</option>
                                    <option value="4WD">Four Wheel Drive (4WD)</option>
                                    <option value="2WD">Two Wheel Drive (2WD)</option>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Condition</label>
                                <select name="condition_type" class="form-select" required>
                                    <option value="New">New</option>
                                    <option value="Used">Used</option>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Body Type</label>
                                <select name="body_type" class="form-select" required>
                                    <option value="">Select Body Type</option>
                                    <option value="Sedan">Sedan</option>
                                    <option value="SUV">SUV</option>
                                    <option value="Hatchback">Hatchback</option>
                                    <option value="Coupe">Coupe</option>
                                    <option value="Wagon">Wagon</option>
                                    <option value="Van">Van</option>
                                    <option value="Truck">Truck</option>
                                    <option value="Convertible">Convertible</option>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Steering</label>
                                <select name="steering" class="form-select" required>
                                    <option value="Left">Left Hand Drive</option>
                                    <option value="Right">Right Hand Drive</option>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Engine Displacement (cc)</label>
                                <input type="number" class="form-control" name="displacement" required>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Model Code</label>
                                <input type="text" class="form-control" name="model_code" placeholder="e.g., E90, W204">
                            </div>

                            <div class="col-12 mb-3">
                                <label class="form-label">Description</label>
                                <textarea class="form-control" name="description" rows="4" required></textarea>
                            </div>

                            <div class="col-12 mb-3">
                                <label class="form-label">Features (one per line)</label>
                                <textarea class="form-control" name="features" rows="4" required></textarea>
                            </div>

                            <div class="col-12 mb-3">
                                <label class="form-label">Images</label>
                                <input type="file" class="filepond" name="images[]" multiple>
                                <input type="hidden" name="uploaded_images" id="uploadedImages" value="[]">
                                <small class="text-muted d-block mt-2">First image will be the main image. Drag to reorder.</small>
                            </div>

                            <div class="col-12">
                                <button type="submit" name="submit" class="btn btn-primary">Add Car</button>
                                <a href="./manage_cars.php" class="btn btn-secondary">Cancel</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Brand change event handler
    $('#brand-select').on('change', function() {
        const brandId = $(this).val();
        const modelSelect = $('#model-select');
        
        if (brandId) {
            $.getJSON('../get_models.php', { brand_id: brandId })
                .done(function(models) {
                    modelSelect.html('<option value="">Select Model</option>');
                    models.forEach(function(model) {
                        modelSelect.append(
                            $('<option>', {
                                value: model.id,
                                text: model.name
                            })
                        );
                    });
                    modelSelect.prop('disabled', false);
                })
                .fail(function(error) {
                    console.error('Error:', error);
                    modelSelect.html('<option value="">Error loading models</option>');
                    modelSelect.prop('disabled', true);
                });
        } else {
            modelSelect.html('<option value="">Select Brand First</option>');
            modelSelect.prop('disabled', true);
        }
    });

    // Auto-fill functionality
    let typingTimer;
    const doneTypingInterval = 1000; // 1 second

    $("#carTitle").on('keyup', function() {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(fetchCarDetails, doneTypingInterval);
    });

    $("#carTitle").on('keydown', function() {
        clearTimeout(typingTimer);
    });

    function fetchCarDetails() {
        const title = $("#carTitle").val();
        if (title.length < 3) return;

        // Extract potential brand and model from title
        const words = title.split(' ');
        let potentialBrand = words[0];
        let potentialModel = words.slice(1).join(' ');

        // Try to find and select brand
        $('#brand-select option').each(function() {
            if ($(this).text().toLowerCase().includes(potentialBrand.toLowerCase())) {
                $('#brand-select').val($(this).val()).trigger('change');
                return false;
            }
        });

        // Fetch from Wikipedia
        $.getJSON("https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&exintro=1&explaintext=1&titles=" + 
            encodeURIComponent(title) + "&origin=*", function(data) {
            if (data.query && data.query.pages) {
                const page = Object.values(data.query.pages)[0];
                if (page.extract) {
                    // Get first 3 sentences
                    let description = page.extract.split('. ').slice(0, 3).join('. ') + '.';
                    $("textarea[name='description']").val(description);

                    // Extract features from Wikipedia text
                    let features = [];
                    const text = page.extract;
                    
                    // Common car feature patterns
                    const patterns = [
                        /(\d+(?:\.\d+)?)[- ]?(?:L|l|cc|CC) engine/g,
                        /(\d+)[- ]?hp|horsepower/g,
                        /(\d+)[- ]?speed (automatic|manual|transmission)/gi,
                        /(front|rear|all)[- ]wheel drive/gi,
                        /(leather|sport|premium|luxury) seats/gi,
                        /(sunroof|moonroof|panoramic roof)/gi,
                        /(navigation|GPS) system/gi,
                        /climate control/gi,
                        /bluetooth/gi,
                        /parking sensors/gi,
                        /backup camera/gi
                    ];

                    patterns.forEach(pattern => {
                        const matches = text.match(pattern);
                        if (matches) {
                            features = features.concat(matches);
                        }
                    });

                    // Add standard features if few were found
                    if (features.length < 5) {
                        features = features.concat([
                            "Power Windows",
                            "Power Steering",
                            "Air Conditioning",
                            "Anti-lock Braking System (ABS)",
                            "Dual Airbags",
                            "Cruise Control",
                            "CD Player",
                            "MP3 Player",
                            "USB Port",
                            "Bluetooth",
                            "Airbags"
                        ]);
                    }

                    $("textarea[name='features']").val(features.join('\n'));
                }
            }
        });

        // First try our car suggestions API
        $.getJSON("get_car_suggestions.php?" + $.param({ search: title }))
            .done(function(data) {
                if (data.success && data.results.length > 0) {
                    const car = data.results[0];
                    fetchCarSpecs(car.brand_name, car.model_name);
                }
            });
    }

    function fetchCarSpecs(make, model) {
        // Using CarQuery API
        $.getJSON(`https://www.carqueryapi.com/api/0.3/?callback=?`, {
            cmd: "getTrims",
            make: make,
            model: model,
            year: "2020"
        })
        .done(function(data) {
            if (data.Trims && data.Trims.length > 0) {
                const car = data.Trims[0];
                
                // Auto-fill description
                let description = `${car.model_year} ${car.make_display} ${car.model_name} ${car.model_trim}. `;
                description += `${car.model_engine_cc}cc ${car.model_engine_type} engine producing ${car.model_engine_power_ps} PS. `;
                description += `${car.model_transmission_type} transmission with ${car.model_drive} drive system. `;
                description += `This ${car.model_body} comes with excellent features and specifications.`;
                
                $("textarea[name='description']").val(description);

                // Auto-fill features
                let features = [];
                if (car.model_engine_type) features.push(car.model_engine_type + " Engine");
                if (car.model_transmission_type) features.push(car.model_transmission_type + " Transmission");
                if (car.model_drive) features.push(car.model_drive + " Drive System");
                if (car.model_body) features.push(car.model_body + " Body Style");
                if (car.model_seats) features.push(car.model_seats + " Seats");
                if (car.model_doors) features.push(car.model_doors + " Doors");
                if (car.model_engine_power_ps) features.push(car.model_engine_power_ps + " PS Power Output");
                
                $("textarea[name='features']").val(features.join("\n"));

                // Set other fields
                if (car.model_drive) {
                    $("select[name='drive_terrain']").val(mapDriveTerrain(car.model_drive));
                }
                if (car.model_body) {
                    $("select[name='body_type']").val(mapBodyType(car.model_body));
                }
                if (car.model_engine_cc) {
                    $("input[name='displacement']").val(car.model_engine_cc);
                }
            }
        });
    }

    function mapBodyType(apiBodyType) {
        const bodyTypeMap = {
            'Sedan': 'Sedan',
            'SUV': 'SUV',
            'Hatchback': 'Hatchback',
            'Coupe': 'Coupe',
            'Wagon': 'Wagon',
            'Van': 'Van',
            'Truck': 'Truck',
            'Convertible': 'Convertible'
        };
        return bodyTypeMap[apiBodyType] || '';
    }

    function mapDriveTerrain(apiDrive) {
        const driveMap = {
            'FWD': 'FWD',
            'Front wheel drive': 'FWD',
            'RWD': 'RWD',
            'Rear wheel drive': 'RWD',
            'AWD': 'AWD',
            'All wheel drive': 'AWD',
            '4WD': '4WD',
            'Four wheel drive': '4WD',
            '4x4': '4x4',
            '2WD': '2WD',
            'Two wheel drive': '2WD'
        };
        return driveMap[apiDrive] || '';
    }

    // Register FilePond plugins
    FilePond.registerPlugin(
        FilePondPluginImagePreview,
        FilePondPluginFileValidateType
    );

    // Initialize FilePond
    const pond = FilePond.create(document.querySelector('.filepond'), {
        allowMultiple: true,
        maxFiles: 10,
        allowReorder: true,
        instantUpload: true,
        acceptedFileTypes: ['image/*'],
        labelFileProcessingComplete: 'Upload complete',
        labelFileProcessingError: 'Upload failed',
        server: {
            process: {
                url: 'upload_image.php',
                method: 'POST',
                onload: (response) => {
                    try {
                        const data = JSON.parse(response);
                        console.log('Upload response:', data);
                        if (data.success) {
                            const uploadedImages = JSON.parse(document.getElementById('uploadedImages').value || '[]');
                            uploadedImages.push(data.path);
                            document.getElementById('uploadedImages').value = JSON.stringify(uploadedImages);
                            console.log('Updated images list:', uploadedImages);
                            return data.path;
                        }
                        console.error('Upload failed:', data.message);
                        return null;
                    } catch (e) {
                        console.error('Parse error:', e, response);
                        return null;
                    }
                }
            },
            revert: {
                url: 'delete_image.php',
                method: 'POST'
            }
        }
    });

    // Form submission validation
    document.querySelector('form').addEventListener('submit', function(e) {
        const uploadedImages = JSON.parse(document.getElementById('uploadedImages').value || '[]');
        if (uploadedImages.length === 0) {
            e.preventDefault();
            alert('Please upload at least one image');
        }
    });
});
</script>

<style>
.upload-container {
    max-width: 900px;
    margin: 0 auto;
}

.filepond--root {
    margin-bottom: 0;
    font-family: 'Poppins', sans-serif;
}

.filepond--panel-root {
    background-color: #f8f9fc;
    border: 2px dashed #4e73df;
    border-radius: 10px;
}

.filepond--drop-label {
    color: #4e73df;
    font-size: 1rem;
    font-weight: 500;
}

.filepond--drop-label label {
    color: #858796;
}

.filepond--item {
    width: calc(25% - 0.5em);
}

.filepond--item-panel {
    background-color: rgba(78, 115, 223, 0.1);
}

.filepond--file-action-button {
    background-color: #fff;
    color: #4e73df;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.filepond--image-preview-wrapper {
    border-radius: 8px;
    overflow: hidden;
}

.filepond--image-preview {
    background: #fff;
}

/* Main image indicator */
.filepond--item:first-child::after {
    content: 'Main Image';
    position: absolute;
    top: -8px;
    right: -8px;
    background: #1cc88a;
    color: white;
    padding: 4px 10px;
    border-radius: 15px;
    font-size: 11px;
    font-weight: 500;
    z-index: 5;
    box-shadow: 0 2px 5px rgba(28, 200, 138, 0.2);
}

.filepond--item:first-child .filepond--item-panel {
    background-color: rgba(28, 200, 138, 0.1);
    border: 2px solid #1cc88a;
}

/* Responsive styles */
@media (max-width: 1200px) {
    .filepond--item {
        width: calc(33.333% - 0.5em);
    }
}

@media (max-width: 992px) {
    .filepond--item {
        width: calc(50% - 0.5em);
    }
}

@media (max-width: 576px) {
    .filepond--item {
        width: 100%;
    }
}

.ui-autocomplete {
    max-height: 300px;
    overflow-y: auto;
    overflow-x: hidden;
    z-index: 9999;
}

.ui-autocomplete .ui-menu-item {
    padding: 5px 10px;
    border-bottom: 1px solid #eee;
}

.ui-autocomplete .ui-menu-item:last-child {
    border-bottom: none;
}

.ui-autocomplete .ui-menu-item div {
    padding: 5px 0;
}

.ui-autocomplete .ui-menu-item small {
    font-size: 0.85em;
    color: #6c757d;
}

.ui-state-active,
.ui-widget-content .ui-state-active {
    border: 1px solid #4e73df;
    background: #4e73df;
    color: white;
}

.custom-file-upload {
    border: 2px dashed #dee2e6;
    padding: 20px;
    border-radius: 8px;
    text-align: center;
    background: #f8f9fa;
}

.upload-controls {
    margin: 20px 0;
}

.progress {
    height: 10px;
    margin-top: 10px;
}

.image-container .card {
    position: relative;
    transition: all 0.3s ease;
}

.image-container .card:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.image-container:first-child::after {
    content: 'Main Image';
    position: absolute;
    top: 0;
    right: 15px;
    background: #1cc88a;
    color: white;
    padding: 2px 10px;
    border-radius: 3px;
    font-size: 12px;
}
</style>

<?php include 'includes/footer.php'; ?> 